import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# from models.student_model import StudentEntity
# from models.teacher_model import TeachersEntity
from sqlalchemy.ext.declarative import declarative_base

import logging
from datetime import datetime

def slow_query_log(conn, cursor, statement, parameters, context, executemany):
    start = datetime.now()
    try:
        return conn._cursor_execute(cursor, statement, parameters, context, executemany)
    finally:
        duration = (datetime.now() - start).total_seconds()
        if duration > 1:  # 超过1秒的查询
            logging.getLogger('sqlalchemy.slow').info(
                f"Slow query ({duration:.3f}s): {statement}"
            )

engine = create_engine(
    "mysql+pymysql://root:123456@localhost:3308/ruanjianbei",
    echo=False,
    connect_args={
        "client_flag": 0,
        "charset": "utf8mb4"
    },
    pool_pre_ping=True,
    pool_recycle=3600
)


Base = declarative_base()
# engine = create_engine("mysql+pymysql://root:123456@localhost:3308/ruanjianbei", echo=True)
# SQLALCHEMY_DATABASE_URL = "mysql+pymysql://username:password@host.docker.internal:3308/ruanjianbei"
# engine = create_engine(SQLALCHEMY_DATABASE_URL)
Base.metadata.create_all(bind=engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_db1():
    db = SessionLocal()
    return db